#include "MediaFileChild.h"
#include <string.h>
#include "x264api.h"
#include <string.h>
MediaFile*OpenMediaFileWithAVC(const char*filename,int FileType){
    MediaFile*mf=NULL;
    int i=0;
    FILE*fp=fopen(filename,"rb");
    if(fp==NULL)return NULL;
    mf=MallocMediaFile();
    mf->FileType=FILE_TYPE_AVC;
    mf->AudioType=VIDEO_TYPE_AVC;
    mf->fp=fp;
    mf->VideoInfo.fps=25;
    while(1){
      uint32_t NextFrameSize=X264GetNextNaluSize(fp);    
      MediaFrame*frame=NULL;
      uint8_t nalu_type=0;
      long pos=0;
      char*buffer=(char*)malloc(NextFrameSize);
      if(NextFrameSize==0)break;
      pos=ftell(mf->fp);
      X264GetNaluBuffer(fp,buffer,NextFrameSize);
      nalu_type=buffer[0]&0x1f;
      if(nalu_type==AVC_NALU_SEQ_PARAM){
         if(mf->AVCInfo.spslen==0){
            mf->AVCInfo.spslen=NextFrameSize;
            mf->AVCInfo.sps=buffer;
            buffer=NULL;
         }
      }else
      if(nalu_type==AVC_NALU_PIC_PARAM){
         if(mf->AVCInfo.ppslen==0){
            mf->AVCInfo.ppslen=NextFrameSize;
            mf->AVCInfo.pps=buffer;            
            buffer=NULL;
         }     
      }else
      if(nalu_type==AVC_NALU_NON_IDR_SLICE||nalu_type==AVC_NALU_IDR_SLICE){
 //     {
         frame=MallocMediaFrame(0);
         frame->pos=pos;
         frame->datalen=NextFrameSize;
         frame->CodecType=VIDEO_TYPE_AVC;
         frame->KeyFrame=nalu_type==AVC_NALU_IDR_SLICE;
         frame->FrameType=FRAME_TYPE_VIDEO;
         frame->timestamp=(uint32_t)i*1000.0/mf->VideoInfo.fps;
         mf->TotalTime=frame->timestamp;
         AddMediaFrame(mf,frame);
         i++;   
      }  
      if(buffer)free(buffer);
    //if(frame)
    //printf("%d %u %u\n",i,NextFrameSize,frame->timestamp);
    //fseek(mf->fp,NextFrameSize,SEEK_CUR);
    }
    mf->CurrentFrame=mf->FrameList;
    return mf;
}